﻿using System;
using System.IO;

namespace NetPublisher
{
    public class PrevFileInfo
    {
        private const int MaxHashLength = 2000000;
        public string FilePath { get; set; }
        public DateTime LastWriteTime { get; set; }
        public long Length { get; set; }

        public int? HashCode { get; set; }

        public PrevFileInfo(){}
        public PrevFileInfo(FileInfo fileInfo)
        {
            FilePath = fileInfo.FullName;
            LastWriteTime = fileInfo.LastWriteTime;
            Length = fileInfo.Length;

            if (fileInfo.Length < MaxHashLength && IsTextFile(fileInfo.Extension))
            {
                using(var sr = fileInfo.OpenText())
                {
                    HashCode = sr.ReadToEnd().GetHashCode();
                }
            }
        }

        public bool IsNewer(FileInfo fileInfo)
        {
            if (Length == fileInfo.Length && LastWriteTime == fileInfo.LastWriteTime)
                return false;
            if (Length == fileInfo.Length && IsTextFile(fileInfo.Extension) /*(fileInfo.Extension.ToUpperInvariant() != ".DLL" && fileInfo.Extension.ToUpperInvariant() != ".EXE") /* && HashCode.GetValueOrDefault() != 0*/)
            {
                using(var sr = fileInfo.OpenText())
                {
                    var newHash = sr.ReadToEnd().GetHashCode();
                    var result = newHash != HashCode;
                    HashCode = newHash;
                    return result;
                }
            }
            return true;
        }

        private bool IsTextFile(string extension)
        {
            switch (extension.ToUpperInvariant())
            {
                case ".TXT":
                case ".HTM":
                case ".HTML":
                case ".JS":
                case ".CS":
                case ".CONFIG":
                case ".XML":
                    return true;
            }
            return false;
        }
    }
}
